<template>
    <a-row justify="space-around">
        <a-col :span="17" style="background-color: #fff; padding: 15px 40px !important; border-radius: 10px;">
            <div class="conditions">
                <div class="condition-item">
                    <div class="condition-label">知识分类：</div>
                    <div class="condition-content">
                        <a-radio-group v-model:value="pageQuery.categoryCode" @change="handlerChangeCategory">
                            <a-space size="small" wrap>
                                <a-radio-button :class="pageQuery.categoryCode === '' ? 'fee-active' : ''"
                                    style="border: none; font-weight: normal;" value="">
                                    全部
                                </a-radio-button>
                                <a-radio-button v-for="item in commonStore.articlesCategoryList" :key="item.dictCode"
                                    :class="pageQuery.categoryCode === item.dictValue ? 'fee-active' : ''"
                                    style="border: none; font-weight: normal;" :value="item.dictValue">
                                    {{ item.dictLabel }}
                                </a-radio-button>
                            </a-space>
                        </a-radio-group>
                    </div>
                </div>
            </div>
            <a-row align="middle" justify="space-between">
                <div class="order-query">
                    <a-tabs v-model:activeKey="order" @change="changeArticleOrder">
                        <a-tab-pane key="" tab="全部" />
                    </a-tabs>
                </div>
                <div class="search-query">
                    <a-input-search class="fish-site-name-input" enter-button v-model:value="pageQuery.title"
                        placeholder="搜索" @search="searchName" />
                </div>
            </a-row>
            <div class="angling-container" v-loading="loading">
                <a-row :gutter="24">
                    <a-col :span="8" class="fish-site-box" v-for="(item, index) in list" :key="item.articleId"
                        @click="openModal(item)">
                        <a-card :title="item.title" hoverable :bordered="false" style="width: 100%">
                            <div>{{ item.description }}</div>
                        </a-card>
                    </a-col>
                </a-row>
                <a-row class="page-box" justify="center">
                    <a-pagination v-model:current="pageQuery.pageNum" v-model:pageSize="pageQuery.pageSize"
                        hideOnSinglePage :showSizeChanger="false" :total="total" show-less-items
                        :show-total="total => `总数 ${total} `" @change="updatePageNum" />
                </a-row>
            </div>
            <a-empty v-show="list.length <= 0">
                <template #description>
                    <span>
                        暂无内容
                    </span>
                </template>
            </a-empty>
        </a-col>
        <a-col :span="6" style="padding-left: 10px;">
            <a-card title="热门钓场" class="hot-comments-card">
                <template v-for="(item, index) in hotFishSiteList" :key="item.fishSiteId">
                    <div class="hot-fish-site-item" @click="toFishSite(item)">
                        <div class="hot-fish-site-index">{{ index + 1 }}</div>
                        <div class="hot-fish-site-content">
                            <div class="hot-fish-site-name">{{ item.name }}</div>
                            <div class="hot-fish-site-info">
                                <span>{{ item.province }} {{ item.city }}</span>
                                <span v-if="item.avgRating" class="rating">
                                    {{ item.avgRating }}
                                    <StarFilled :style="{ color: '#F7BA2A', fontSize: '12px' }" />
                                </span>
                            </div>
                        </div>
                    </div>
                    <a-divider v-if="index !== hotFishSiteList.length - 1" style="margin: 12px 0" />
                </template>
            </a-card>
            <!-- <a-card title="热门帖子" class="hot-comments-card" style="margin-top: 25px;">
               
            </a-card> -->
        </a-col>
    </a-row>

    <!-- 使用登录提示模态框组件 -->
    <login-tooltip-mode ref="loginModal" />
    <!-- ai聊天框，有时间可以做成弹出侧边栏出现al聊天，然后侧边栏在选择全屏聊天 -->
    <a-float-button @click="handleAiChat" shape="circle" type="primary" :style="{
        right: '94px',
    }">
        <template #icon>
            <CommentOutlined />
        </template>
        <template #tooltip>
            <div>AI聊天</div>
        </template>
    </a-float-button>
    <!-- 模态框组件 -->
    <a-modal v-model:open="modalVisible" title="文章详情" width="100%" wrap-class-name="full-modal" centered
        @ok="modalVisible = false" @cancel="modalVisible = false" mask="false" maskClosable="false" :footer="null">
        <div v-html="sanitizeHtml(currentArticle.content)"></div>
    </a-modal>

</template>

<script setup lang="ts">
import '@/styles/article.scss';
import '@/styles/angling.scss';
import { AnglingQuery, AnglingVO } from "@/api/front/angling/types";
import { useRouter } from 'vue-router';
import DOMPurify from 'dompurify';
import type { SelectProps } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { anglingList, searchOptions } from "@/api/front/angling";
import { StarFilled, CommentOutlined } from '@ant-design/icons-vue';
import { useUserStore } from '@/store/modules/user';
import LoginTooltipMode from '@/components/LoginTooltipMode/index.vue';
import { useCommonStore } from '@/store/modules/common';
import { articlesDetailView, articlesList } from '@/api/front/articles';
import { ArticleVo } from '@/api/front/articles/types';
import { hotList } from '@/api/front/social';
import { HotListVO } from '@/api/front/social/types';

let loading = ref(false)
let order = ref("")
let total = ref(0)
const formDataRef = ref<FormInstance>();
const commonStore = useCommonStore();
const router = useRouter()

const pageQuery = reactive({
    pageSize: 10,
    pageNum: 1,
    orderByColumn: '',
    isAsc: 'desc',
    categoryCode: '',
    title: ''
})

let list = reactive<Array<ArticleVo>>([])
let hotFishSiteList = ref<Array<AnglingVO>>([])
let modalVisible = ref(false)
let currentArticle = ref<ArticleVo | null>(null)
let messages = ref<Array<{ id: number; content: string; isUser: boolean }>>([])
const chatInput = ref('')

const sendChat = () => {
    console.log(chatInput.value)
    if (chatInput.value.trim() !== '') {
        messages.value.push({ id: Date.now(), content: chatInput.value, isUser: true })
        chatInput.value = '' // 清空输入框
        setTimeout(() => {
            messages.value.push({ id: Date.now(), content: "这是AI的回答", isUser: false })
        }, 1000)
    }
}

/**
 * 监听pageNum变化
 */
const updatePageNum = (value: number) => {
    getArticleList()
}

/**
 * 切换钓点排序
 * @param activeKey
 */
const changeArticleOrder = (activeKey: string) => {

}
//过滤html标签
const sanitizeHtml = (content) => {
    return DOMPurify.sanitize(content);
}


const truncateContent = (content, maxLength) => {
    const tempElement = document.createElement('div');
    tempElement.innerHTML = content;
    const text = tempElement.innerText || tempElement.textContent;

    return text.length > maxLength
        ? text.slice(0, maxLength) + '...'
        : text;
}

const handleAiChat = () => {
    router.push('/chat')
}

/**
 * 初始化页面
 */
const getArticleList = async () => {
    loading.value = true
    const res = await articlesList(pageQuery)
    list.splice(0, list.length, ...res.data.rows);
    total.value = res.data.total
    loading.value = false
}

const handlerChangeCategory = (value: string) => {
    getArticleList()
};


const searchName = (value: string) => {
    getArticleList()
}

const userStore = useUserStore()

const toFishSite = (fishSite: AnglingVO) => {
  // 检查用户是否登录
  if (!userStore.userId) {
    loginModal.value?.show();
    return;
  }

  // 已登录则正常跳转
  const routeUrl = router.resolve({
    name: '钓场详情',
    params: {
      fishSiteId: fishSite.fishSiteId
    }
  });
  window.open(routeUrl.href, '_blank');
}

const getHotFishSiteList = async () => {
    const query = {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'rating_count',
        isAsc: 'desc'
    }
    const res = await anglingList(query, {})
    hotFishSiteList.value = res.data.rows
}
const hotPostsList = ref<Array<HotListVO>>([])
const getHotPostsList = async () => {
    const res = await hotList({
        categoryCode: 0,
        pageNum: 1,
        pageSize: 10,
    });
    hotPostsList.value = res.data
}


const updateArticleView = async (articleId: string) => {
    await articlesDetailView({ articleId })
}

const loginModal = ref();

// 打开模态框并设置当前文章
const openModal = (article: ArticleVo) => {
    currentArticle.value = article;
    modalVisible.value = true;
    updateArticleView(article.articleId)
};

const getImageUrls = (imageUrl: string) => {
    if (!imageUrl) return [];
    return imageUrl.includes(',') ? imageUrl.split(',') : [imageUrl];
}

onMounted(() => {
    getArticleList()
    getHotFishSiteList()
    getHotPostsList()
    commonStore.getCommonData()
})

</script>

<style scoped lang="scss">
.conditions {
    border-bottom: 1px solid #F0F0F0;
    padding: 15px 0;

    .condition-item {
        margin-bottom: 15px;
        display: flex;
        align-items: flex-start;

        .condition-label {
            width: 9.33%;
            margin-right: 15px;
            font-weight: bolder;
            color: #555;
            line-height: 32px;
            text-align: right;
        }

        .condition-content {
            flex: 1;
        }
    }

    .ant-radio-button-wrapper {
        padding-inline: 10px;
        margin-bottom: 8px;

        &:hover {
            color: #1890ff;
            background: #e6f7ff;
        }
    }

    .fee-active {
        color: #1890ff !important;
        background: #e6f7ff !important;
    }
}

.angling-container {
    margin-top: 20px;

    .fish-site-box {
        margin-top: 20px;

        .fish-site-name {
            padding-right: 3px;
            color: #1d1e1f;
        }

        .fish-site-avg-rating {
            display: flex;
            align-items: center;

            span {
                margin-right: 5px;
            }
        }
    }

    .page-box {
        margin-top: 25px;
    }
}

.hot-fish-site-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    cursor: pointer;

    &:hover {
        .hot-fish-site-name {
            color: #1890ff;
        }
    }

    .hot-fish-site-index {
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        background-color: #f0f0f0;
        border-radius: 4px;
        margin-right: 12px;
        font-weight: bold;
    }

    .hot-fish-site-content {
        flex: 1;

        .hot-fish-site-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .hot-fish-site-info {
            font-size: 12px;
            color: #999;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .rating {
                display: flex;
                align-items: center;
                gap: 4px;
            }
        }
    }
}

.hot-comments-card {
    width: 100%;
    border-radius: 20px;
    background: #fff;

    :deep(.ant-card-head) {
        background: linear-gradient(180deg, #e6f7ff 0%, #ffffff 100%);
        border-bottom-color: rgba(0, 0, 0, 0.1);

        .ant-card-head-title {
            color: #1890ff;
            font-weight: bold;
        }
    }
}

.full-screen-modal .ant-modal-content {
    height: 100vh;
    /* 设置模态框内容高度为视口高度 */
    overflow-y: auto;
    /* 内容超出时可滚动 */
}


</style>